package com.zx.springcloud.controller;


import com.zx.springcloud.entities.CommonResult;
import com.zx.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class OrderController {
    //public static final String PYAMENT_URL = "http://localhost:8001";
    public static final String PYAMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        CommonResult commonResult = restTemplate.postForObject(PYAMENT_URL + "/payment/create", payment, CommonResult.class);

        return commonResult;
    }
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PYAMENT_URL + "/payment/get/" + id,CommonResult.class);
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        //获取所有的服务列表
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("========================================service: " + service);
        }

        //根据已知的服务名称返回服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getInstanceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }

        return this.discoveryClient;
    }
}
